<?php

require_once("config.php");

/**
 * Class used to performing actions
 * @author shenlon
 */
abstract class Controller {

    /**
     * Controller name
     * @var String
     */
    private $name;

    /**
     * View used to display content
     * @var View
     */
    private $view;

    /**
     * File with current action content
     * @var type 
     */
    private $contentFile;

    /**
     * Basket used in store
     * @var Basket
     */
    private $basket;

    /**
     * Default constructor
     * @param string $name
     * @param Array $options 
     */
    public function __construct($name, $options = array('templateFile' => 'style/template.phtml')) {
        $this->name = $name;
        $this->view = new View($options['templateFile']);
        $this->basket = new Basket();
        $this->view->basket = $this->basket;
        $this->view->categories = Product::listCategories();
        $action = "Default";
        if (isset($_GET['action'])) {
            $action = $_GET['action'];
            if (!file_exists($this->getFileName($action)))
                $action = "Error";
        }
        $this->performAction($action);
    }

    /**
     * Loads a file proper for the action name
     * @param string $actionName
     * @throws Exception 
     */
    public function performAction($actionName) {
        $name = $this->getFileName($actionName);
        if (file_exists($name)) {
            if (is_readable($name)) {
                require_once($name);
                echo $this->view->render($this->contentFile);
            } else
                throw new Exception("Can't read file $name");
        } else {
            $this->name = 'Index';
            require_once($this->getFileName('Error'));
            echo $this->view->render("404");
        }
    }

    /**
     * Returns file name for speciffied action name
     * @param string $actionName
     * @return string
     */
    private function getFileName($actionName) {
        return "Action/{$this->name}/{$actionName}Action.php";
    }

}

?>
